<?php

namespace Frieza\Modules\Feedback\Controllers;


use Encore\Admin\Grid;
use Illuminate\Http\Request;
use Biz\tools\helper\Common;
use Encore\Admin\Widgets\Tab;
use App\Pockets\GridDataModel;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use Illuminate\Support\MessageBag;
use App\Http\Controllers\Controller;
use Doraemon\model\ConfManager\SameWord;
use Doraemon\model\ConfManager\Question;
use Doraemon\model\ConfManager\HhzEsQaPair;
use Doraemon\model\ConfManager\AnswerList;
use Doraemon\model\ConfManager\ConfManagerMysql;
use Frieza\Modules\Topic\Extensions\Widgets\Form;

class FeedBackController extends Controller
{
    private const  PROJECT_CODE = 'inner:202012:robot_reply_user_dict';
    private const  PROJECT_NAME = '用户反馈话术';
    private const  PROJECT_TYPE = 'inner';

    private const PAGE_SIZE = 50;

    public const UPDATE_QA_ANSWER = 1;
    public const UPDATE_SAME_WORD = 2;

    /**
     *  反馈列表
     */
    public function index(Request $request, Content $content): Content
    {
        $params = $request->all();
        $page_size = $params['per_page'] ?? self::PAGE_SIZE;
        $page = $params['page'] ?? 1;
        $where['LIMIT'] = [
            ($page - 1) * $page_size,
            $page_size,
        ];
        $list = AnswerList::dataSelect($where);
        foreach ($list as &$temp) {
            $temp['list'] = $aList[$temp['id']] ?? [];
        }
        unset($temp);
        unset($where['LIMIT']);
        $count = AnswerList::dataCount($where);
        $gridModel = new GridDataModel($list, $count, [
            'perPage' => $page_size,
        ]);
        $grid = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
//                $grid->disableCreateButton();
                $grid->disableFilter();
//                //显示当前页的序号
//                $grid->number('序号');
//                $grid->rows(function ($row, $number) {
//                    $row->column('number', $number + 1);
//                });

                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->column('id', 'ID');
                $grid->column('question', '问题')->display(function () {
                    $aQuestion = json_decode($this->question,true);
                    foreach ($aQuestion as $item) {
                        $html .= '<div class="span-label" style="margin-bottom: 5px"><span class="label label-success">' . $item . '</span></div>';
                    }
                    return $html;
                });
                $grid->column('answer', '答案')->width(400);
                $grid->column('data_status', '删除状态')->using(
                    [
                        AnswerList::STATUS_DELETE => '已删除',
                        AnswerList::STATUS_ON => '正常',
                    ]
                )->label([
                    2 => 'danger',
                    1 => 'success',
                ]);
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableDelete();
                });
            }
        );
        $tab = new Tab();
        $tab->add('答案问题列表', $grid->render(), true);
        $tab->addLink('近义词', url('/admin/feedback/list/sameword'), false);
        $tab->addLink('字典&停用词', url('/admin/feedback/list/stoplist'), false);
//        $tab->addLink('元配置', url('/admin/feedback/list/yaml'), false);


        $content->row($tab);

        return $content
            ->header('答案问题列表')
            ->description(' ')
            ->breadcrumb(['text' => '问题反馈配置', 'url' => '/feedback/list']);
    }


    public function create(Form $form, Content $content)
    {
        $form->textarea('answer', '答案！');
        $form->list('question','问题');
        $form->action('/admin/feedback/list/save');
        return $content
            ->header('答案-新增')
            ->description(' ')
            ->breadcrumb(
                ['text' => '答案问题列表', 'url' => '/feedback/list'],
                ['text' => '新增']
            )
            ->row($form);
    }

    public function edit( Content $content, $id)
    {
        $aAnswer = AnswerList::dataSelectInfo(['id'=>$id]);
        $aQuestion = array_values (json_decode($aAnswer['question'],true))?:[];
        $aAnswer['question'] = $aQuestion;
        $form = new Form($aAnswer);
        $form->hidden('id', 'ID')->default($aAnswer['id']);
        $form->textarea('answer', '答案！')->default($aAnswer['answer']);
        $form->list('question','问题')->default($aQuestion);

        $form->action('/admin/feedback/list/save');
        return $content
            ->header('答案-修改')
            ->description(' ')
            ->breadcrumb(
                ['text' => '答案问题列表', 'url' => '/feedback/list'],
                ['text' => '修改']
            )
            ->row($form);

    }

    public function Save(Request $request)
    {
        try {
            $aParams = $request->all();
            $rules = [
                "answer" => 'required',
            ];
            //校验参数
            $res_msg = Common::validatorRule($rules, $aParams);
            if ($res_msg !== true) {
                throw new \Exception($res_msg);
            }
            if (empty($aParams['question']['values'])) {
                throw new \Exception('问题不能为空');
            }
            $data = [
                'answer' => $aParams['answer'],
                'question' => json_encode($aParams['question']['values'], JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE),
                "admin_name" => Admin::user()->name,
            ];
            if ($aParams['id']) {
                // 编辑，需要先查出原来的老的数据，再和新的数据进行对比
                $aAnswer = AnswerList::dataSelectInfo(['id'=>$aParams['id']]);
                $aQuestion = array_values (json_decode($aAnswer['question'],true))?:[];
                foreach ($aQuestion as $old) {
                    if (!in_array($old, $aParams['question']['values'])) {
                        // 需要进行删除
                        HhzEsQaPair::delete(['question' => $old, 'owner_name' => '社区话术', 'q_id' => $aParams['id']]);
                    } else {
                        // 需要进行更新
                        HhzEsQaPair::update(['answer' => str_replace("###", "\n", $aParams['answer']), 'edit_time' => time()],
                            ['question' => $old, 'owner_name' => '社区话术', 'q_id' => $aParams['id']]);
                    }
                }
                $needInsert = array_diff($aParams['question']['values'], $aQuestion);
                AnswerList::update($data, ['id' => $aParams['id']]);
            } else {
                $needInsert = $aParams['question']['values'];
                $aParams['id'] = AnswerList::dataInsert($data);
                if ($aParams['id'] == false) {
                    throw new \Exception('插入失败');
                }
            }

            foreach ($needInsert as $new) {
                HhzEsQaPair::insert([
                    'q_id' => $aParams['id'],
                    'question' => $new,
                    'answer' => str_replace("###", "\n", $aParams['answer']),
                    'owner_name' => '社区话术',
                    'add_time' => time(),
                    'edit_time' => time(),
                    'op_status' => 5,
                ]);
            }

            $success = new MessageBag([
                'title' => '成功',
            ]);
            $this->syncData(self::UPDATE_QA_ANSWER);
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage(),
            ]);
            return back()->with(compact('error'))->withInput();
        }
        return redirect('/admin/feedback/list')->with(compact('success'));

    }


    public function sameWordList(Request $request, Content $content): Content
    {
        $params = $request->all();
        $page_size = $params['per_page'] ?? self::PAGE_SIZE;
        $page = $params['page'] ?? 1;
        $where['LIMIT'] = [
            ($page - 1) * $page_size,
            $page_size,
        ];
        $list = SameWord::dataSelect($where);
        unset($where['LIMIT']);
        $count = AnswerList::dataCount($where);
        $gridModel = new GridDataModel($list, $count, [
            'perPage' => $page_size,
        ]);
        $grid = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->disableFilter();
                $grid->disableActions();
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->column('id', 'ID');
                $grid->column('ori_word', '词')->editable();
                $grid->column('same_word', '近义词')->editable()->help('多个用，英文逗号隔开');
                $grid->column('data_status', '状态')->using(
                    [
                        AnswerList::STATUS_DELETE => '已删除',
                        AnswerList::STATUS_ON => '正常',
                    ]
                )->label([
                    2 => 'danger',
                    1 => 'success',
                ]);
            }
        );
        $tab = new Tab();
        $tab->addLink('答案问题列表', url('/admin/feedback/list'), false);
        $tab->add('近义词', $grid->render(), true);
        $tab->addLink('字典&停用词', url('/admin/feedback/list/stoplist'), false);
//        $tab->addLink('元配置', url('/admin/feedback/list/yaml'), false);

        $content->row($tab);

        return $content
            ->header('近义词列表')
            ->description(' ')
            ->breadcrumb(['text' => '问题反馈配置', 'url' => '/feedback/list']);
    }


    public function sameWordEdit($id, Request $request)
    {
        try {
            $params = $request->all();

            $rule = [
                'name' => 'required|string',
                'value' => 'required',
                'pk' => 'required|int',
            ];
            $validator_msg = Common::validatorRule($rule, $params);
            if ($validator_msg !== true) {
                throw  new \Exception($validator_msg);
            }
            if (!in_array($params['name'], ['same_word', 'ori_word'])) {
                throw  new \Exception('异常操作');
            }
            $admin_id = Admin::user()->id;

            if ($params['name'] === 'same_word') {
                $data['same_word'] = $params['value'];
            } else {
                $data['ori_word'] = $params['value'];
            }
            $data['admin_id'] = $admin_id;
            $info = SameWord::dataSelectInfo(['id' => $params['pk']]);
            if (empty($info)) {
                throw new \Exception('不存在的词');
            }
            SameWord::dataUpdate($data, ['id' => $params['pk']]);
            $success = [
                'message' => '操作成功',
                'status' => true,
            ];
            $this->syncData(self::UPDATE_SAME_WORD);
        } catch (\Exception $e) {
            $success = [
                'message' => '操作失败,' . $e->getMessage(),
                'status' => false,
            ];
        }

        return response()->json($success);
    }


    public function sameWordCreate(Content $content)
    {
        $form = new Form();

        $form->text('ori_word', '词');
        $form->text('same_word', '近义词')->help('多个用，英文逗号隔开');
        $form->action('/admin/feedback/list/sameword/save');
        return $content
            ->header('近义词-新增')
            ->description(' ')
            ->breadcrumb(
                ['text' => '近义词列表', 'url' => '/feedback/list/sameword'],
                ['text' => '新增']
            )
            ->row($form);

    }


    public function sameWordSave(Request $request)
    {
        try {
            $params = $request->all();
            $rules = [
                "text" => 'required',
                "same_word" => 'required',
            ];
            //校验参数
            $res_msg = Common::validatorRule($rules, $params);
            if ($res_msg !== true) {
                throw new \Exception($res_msg);
            }
            $data = [
                "text" => $params["text"] ?? '',
                "same_word" => $params["same_word"] ?? '',
                "admin_id" => Admin::user()->id,
            ];
            $success = new MessageBag([
                'title' => '成功',
            ]);
            SameWord::dataInsert($data);
            $this->syncData(self::UPDATE_SAME_WORD);
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage(),
            ]);
            return back()->with(compact('error'))->withInput();
        }
        return redirect('/admin/feedback/list/sameword')->with(compact('success'));

    }


    public function stopList(Content $content)
    {

        $aWhere = ['project_code' => self::PROJECT_CODE];
        $aInfo = ConfManagerMysql::getDataByWhere('*', $aWhere);
        $aDataTemp = $aInfo['value'] ? json_decode($aInfo['value'], true) : [];

        $aData = [
            'dict' => $aDataTemp['dict'] ?? '',
            'stop_word' => $aDataTemp['stop_word'] ?? '',
        ];

        $form = new Form($aData);

        $tab = new Tab();
        $tab->addLink('答案问题列表', url('/admin/feedback/list'), false);
        $tab->addLink('近义词', url('/admin/feedback/list/sameword'), false);
        $tab->addLink('字典&停用词', url('/admin/feedback/list/stoplist'), true);
//        $tab->addLink('元配置', url('/admin/feedback/list/yaml'), false);
//        $content->row($tab);

        $form->text('dict', '字典');
        $form->textarea('stop_word', '停用词')->help('多个用英文空格隔开！');
        $form->action('/admin/feedback/list/stoplist/save');
        return $content
            ->header('字典&停用词')
            ->description(' ')
            ->breadcrumb(
                ['text' => '答案问题列表', 'url' => '/feedback/list'],
                ['text' => '编辑']
            )
            ->row($form);
    }


    public function stopSave(Request $request)
    {
        try {
            $params = $request->all();
            $rules = [
                "dict" => 'required',
                "stop_word" => 'required',
            ];
            //校验参数
            $res_msg = Common::validatorRule($rules, $params);
            if ($res_msg !== true) {
                throw new \Exception($res_msg);
            }

            $aWhere = ['project_code' => self::PROJECT_CODE];
            $aInfo = ConfManagerMysql::getDataByWhere('*', $aWhere);

            $aDataTemp = $aInfo['value'] ? json_decode($aInfo['value'], true) : [];
            $aDataTemp['dict'] = $params["dict"] ?: '';
            $aDataTemp['stop_word'] = $params["stop_word"] ?: '';

            $aUpData['value'] = json_encode($aDataTemp, JSON_UNESCAPED_UNICODE);
            $aUpData['update_username'] = Admin::user()->username;
            ConfManagerMysql::updateData($aUpData, $aWhere);
            $success = new MessageBag([
                'title' => '成功',
            ]);

        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage(),
            ]);
            return back()->with(compact('error'))->withInput();
        }
        return redirect('/admin/feedback/list/stoplist')->with(compact('success'));

    }

    public function syncData($type)
    {

        $aWhere = ['project_code' => self::PROJECT_CODE];
        $aInfo = ConfManagerMysql::getDataByWhere('*', $aWhere);

        switch ($type) {
            case self::UPDATE_QA_ANSWER:
                $list = AnswerList::dataSelect([], ['id', 'question', 'answer', 'admin_name']);
                $qaList = [];
                foreach ($list as $key => $temp) {
                    $qaList[$key]['admin_name'] = $temp['admin_name'];
                    $qaList[$key]['answer'] = $temp['answer'];
                    $aQaList = $temp['question'] ? json_decode($temp['question'], true) : [];
                    foreach ($aQaList as $i => $iValue) {
                        $qaList[$key]['question_' . ($i + 1)] = $iValue;
                    }
                }
                $aData = json_decode($aInfo['value'], true);
                $aData['qa_list'] = $qaList;
                $aUpData['value'] = json_encode($aData, JSON_UNESCAPED_UNICODE);
                ConfManagerMysql::updateData($aUpData, $aWhere);
                break;
            case self::UPDATE_SAME_WORD:
                $list = SameWord::dataSelect([]);
                $qaList = [];
                foreach ($list as $key => $item) {
                    $qaList[]['ori_word'] = $item['ori_word'];
                    $sameWord = $item['same_word'] ? explode(',', $item['same_word']) : [];
                    foreach ($sameWord as $i => $word) {
                        $qaList[$key]['sameword_' . ($i + 1)] = $word;
                    }
                }
                $aData = json_decode($aInfo['value'], true);
                $aData['sameword_list'] = $qaList;
                $aUpData['value'] = json_encode($aData, JSON_UNESCAPED_UNICODE);
                ConfManagerMysql::updateData($aUpData, $aWhere);
                break;
        }
    }



    //
//    public function yamlConfig(Content $content)
//    {
//        $aInfo = ConfManagerMetaMysql::getDataByWhere('*', ['project_code' => 'inner:202012:robot_reply_user_dict']);
//        $form = new Form($aInfo);
//        $tab = new Tab();
//        $tab->addLink('答案问题列表', url('/admin/feedback/list'), false);
//        $tab->addLink('近义词', url('/admin/feedback/list/sameword'), false);
//        $tab->addLink('字典&停用词', url('/admin/feedback/list/stoplist'), false);
//        $tab->addLink('元配置', url('/admin/feedback/yaml/config'), true);
//        $content->row($tab);
//        $form->textarea('value', '字典');
//        $form->hidden('project_type', 'inner');
//        $form->hidden('project_code', 'inner:202012:robot_reply_user_dict');
//        $form->hidden('project_name', '用户反馈话术');
//        $form->action('/admin/feedback/list/yaml/save');
//        return $content
//            ->header('元配置')
//            ->description(' ')
//            ->breadcrumb(
//                ['text' => '近义词列表', 'url' => '/feedback/list/sameword'],
//                ['text' => '编辑']
//            )
//            ->row($form);
//    }
//
//    public function yamlSave(Request $request)
//    {
//        try {
//            $aParams = $request->all();
//            $rules = [
//                "project_code" => 'required',
//                "value" => 'required',
//            ];
//            //校验参数
//            $res_msg = Common::validatorRule($rules, $aParams);
//            if ($res_msg !== true) {
//                throw new \Exception($res_msg);
//            }
//            $where['project_code'] = $aParams['project_code'];
//            $data = [
//                'value' => $aParams['value'],
//                "update_username" => Admin::user()->username,
//            ];
//            ConfManagerMetaMysql::updateData($data, $where);
//            $success = new MessageBag([
//                'title' => '成功',
//            ]);
//
//        } catch (\Exception $e) {
//            $error = new MessageBag([
//                'title' => $e->getMessage(),
//            ]);
//            return back()->with(compact('error'))->withInput();
//        }
//        return redirect('/admin/feedback/list/yaml')->with(compact('success'));
//
//    }



}